package com.xiaozhengkeji.mc.plugins.cdkey.commands;

import com.xiaozhengkeji.mc.plugins.cdkey.base.BaseFactory;
import com.xiaozhengkeji.mc.plugins.cdkey.base.SQLiteFactory;
import com.xiaozhengkeji.mc.plugins.cdkey.config.HelpConfig;
import com.xiaozhengkeji.mc.plugins.cdkey.entitys.CDKeyEntity;
import com.xiaozhengkeji.mc.plugins.cdkey.service.CDKeyService;
import com.xiaozhengkeji.mc.plugins.cdkey.utils.DaysUtil;
import com.xiaozhengkeji.mc.plugins.cdkey.utils.MsgUtils;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.sql.SQLException;
import java.util.List;

public class PlayerCommands implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            MsgUtils.logServer("请在客户端使用!");
            return true;
        }
        Player p = (Player) sender;
        if (args.length == 0) {
            HelpConfig.Player_Help.forEach(help -> MsgUtils.logPlayer(p, help));
            return true;
        }

        CDKeyEntity cdKeyEntity = new SQLiteFactory().getCDKeyByCDKey(args[0]);
        if (cdKeyEntity == null) {
            MsgUtils.logPlayer(p, "未找到本CDK");
            return true;
        }
        if (!cdKeyEntity.open_player.equalsIgnoreCase("")) {
            MsgUtils.logPlayer(p, "本CDK已经使用");
            return true;
        }
        //先更新
        cdKeyEntity.setOpen_player(p.getUniqueId().toString());
        cdKeyEntity.setUp_date(DaysUtil.getDate());
        new SQLiteFactory().upCDKey(cdKeyEntity);
        //开始发放
        List<String> cs = new BaseFactory().getCB(cdKeyEntity.b_commands);
        cs.forEach(c -> new CDKeyService().consoleActuator(c, p));
        MsgUtils.logPlayer(p, "兑换完成!");
        return true;

    }
}
